<template>
  <div class="stats-page">
    <h1>用户喜好占比分析</h1>
    <div class="user-info">
      <h2>用户ID: {{ userId }}</h2>
      <router-link to="/" class="back-btn">返回列表</router-link>
    </div>

    <div class="chart-container">
      <!-- 使用第三方图表库（ECharts） -->
      <div ref="chartEl" style="width: 600px; height: 400px;"></div>
    </div>

    <div class="data-table">
      <table>
        <thead>
        <tr>
          <th>标签</th>
          <th>占比</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(value, key) in statsData" :key="key">
          <td>{{ key }}</td>
          <td>
            <div class="percentage-bar" :style="{ width: value + '%' }"></div>
            <span>{{ value }}%</span>
          </td>
        </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import * as echarts from 'echarts'
import Service from '@/router/interceptor.js'
import { ElMessage } from 'element-plus'

const route = useRoute()
const userId = route.params.userId
const chartEl = ref(null)

// 模拟数据（保留作为后备）
const mockData = {
  科技: 80,
  娱乐: 15,
  教育: 5
}

const statsData = ref({})

// 初始化图表和数据获取
onMounted(async () => {
  try {
    const response = await Service.get(`/api/userFlavor/loadDataList`,{
      params:{
        uid: userId
      }
    })
    console.log('后端响应:', response)  // 保留调试日志
    
    if (response.code === 200 && response.data?.list.length > 0) {
      // 转换数组数据格式为 { 标签: 百分比 }
      const backendData = response.data.list.reduce((acc, cur) => {
        acc[cur.tname] = (cur.tpercent * 100).toFixed(0) // 将0.15转换为15%
        return acc
      }, {})
      statsData.value = backendData
    } else {
      statsData.value = mockData // 使用模拟数据
    }
  } catch (error) {
    ElMessage.error('数据加载失败，使用模拟数据')
    statsData.value = mockData // 网络异常时使用模拟数据
  }

  // 初始化图表
  const chart = echarts.init(chartEl.value)
  chart.setOption({
    tooltip: {
      trigger: 'item'
    },
    series: [{
      name: '喜好占比',
      type: 'pie',
      radius: '70%',
      data: Object.entries(statsData.value).map(([name, value]) => ({
        name,
        value
      })),
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  })
})
</script>

<style scoped>
.stats-page {
  max-width: 800px;
  margin: 0 auto;
  padding: 30px;
}

.user-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.back-btn {
  padding: 8px 16px;
  background: #f0f0f0;
  border-radius: 4px;
  text-decoration: none;
  color: #333;
}

.chart-container {
  margin: 40px 0;
  display: flex;
  justify-content: center;
}

.data-table {
  margin-top: 30px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

.percentage-bar {
  display: inline-block;
  height: 20px;
  background: #4CAF50;
  margin-right: 10px;
  vertical-align: middle;
}
</style>